# plugs/links.py
#
#

""" link <item> to <otheritem> """

__status__ = "seen"

## gozerbot imports

from gozerbot.commands import cmnds
from gozerbot.redispatcher import rebefore
from gozerbot.plughelp import plughelp
from gozerbot.examples import examples
from gozerbot.persist.pdol import Pdol
from gozerbot.datadir import datadir

## basic imports

import os

## plughelp

plughelp.add('links', 'alias items to other items .. this is only used in karma for now')

## defines

links = Pdol(datadir + os.sep + 'links')

## links-add command

def handle_linksadd(bot, ievent):
    """ links-add <item> = <otheritem> """
    try: (item, otheritem) = ievent.groups
    except ValueError: ievent.missing('<item> = <otheritem>') ; return
    links.add(item, otheritem)
    links.save()
    ievent.reply('%s link added' % otheritem)

rebefore.add(5, 'links-add (.*?) = (.*)', handle_linksadd, 'USER')
examples.add('links-add', 'links-add <from> = <to> .. add a link', 'links-add mekker = miep bla')

## links-del command

def handle_linksdel(bot, ievent):
    """ links-del <item> = <otheritem> """
    try: (item, linkto) = ievent.groups
    except ValueError: ievent.missing('<item> = <link>') ; return
    itemlist = links[item]
    if not itemlist: ievent.reply('no links available for %s' % item) ; return
    for i in range(len(itemlist)-1, -1, -1):
        if itemlist[i] == linkto:
            del itemlist[i]
            links.save()
            ievent.reply('%s deleted' % linkto)
            return
            
rebefore.add(5, 'links-del (.*?) = (.*)', handle_linksdel, ['LINKS', 'OPER'])
examples.add('links-del', 'links-del <from> = <to> .. delete a link', \
'links-del mekker = miep bla')

## links-list command

def handle_linkslist(bot, ievent):
    """ links-list <item> .. show link of <item> """
    if not ievent.rest: ievent.missing('<item>') ; return
    result = links[ievent.rest]
    if result: ievent.reply("links for %s: " % ievent.rest, result)
    else: ievent.reply('no links found for %s' % ievent.rest)

cmnds.add('links-list', handle_linkslist, 'USER')
examples.add('links-list', 'links-list <item> .. show link of <item>', 'links-list mekker')

#### BHJTW 22-01-2012
